/**
 * Description:该类主要用于创建一个自动匹配的输入框 
 * Copyright: 成都和为科技有限公司 2012
 * 属性：
 *   datasource  - 数据资源.
 *   type - 默认为data. 如果code 自动加上valuetag,displaytag,querytag,attributetag,submittag.  可选data
 *   coderes -
 *   suggestwidth - 建议输入框宽度
 *   mustmatch - 是否必须选中。否则清空输入框
 *   check - 是否支持多选 true|false
 *   async - 默认false, 是否异步加载编码树
 *   valuetag - 当数据资源为DataService时,提交给服务器的标记值
 *   attributetag - 当数据资源为DataService时, 显示在建议下拉列表的属性，可用逗号分隔
 *   displaytag - 当数据资源为DataService时, 显示在建议下拉列表的值
 *   querytag - 当数据资源为DataService时, 提交给服务器的查询参数名字.
 *   submittag - 除了提交valuetag到服务器，还会组装submittag内容到服务器.
 *      如:path="sex", submittag="{'name':'sexname'}"  服务器端接收到的数据为sex:男, sexname:1
 *   showicon - 显示小图标，默认为true
 *   selfvalidate - 调用自带认证方法，默认为true
 *   parentallow - 允许选择父节点，默认为false
 *   placement - 工具栏位置, 默认bottom
 *   params - 查询参数
 *   iconclickreload - 点击小图标重查询展开内容. 默认为false
 *   defineaction - 当数据类型为data, 点击查询小图标自动弹出表格.
 *      后台配置查询表格定义action
 *   idTag - 数据节点标识,用于构建树，也就是type=code类型，默认为id
 *   pidTag - 父数据节点标识,用于构建树，也就是type=code类型,默认为pid
 *   tableRowNum - 下拉表格显示行数
 *   autocompleterownum -自动填充的行数.
 *   focusshow - 聚焦显示结果, 默认为false
 *   usecache  -使用cache的标志,比如外来人员进去不能使用cache
 *   
 * 事件:
 *   formatitem - 格式化下拉内容
 *   initdata - 查询结果数据后调用初始化数据
 *   beforequery - 在查询前触发事件
 *   beforeselect - 选中数据前调用事件
 *   itemselect - 当选中一个值，调用该事件. 参数为：选择值的JSON数据
 *   onkeydown - 按键事件
 *   iconclick - 点击小图标调用
 *   gridselectall - 展开表格全选
 */
function SuggestInput() {
}

SuggestInput.inherit(Input);

/**
 * 初始化方法
 */
SuggestInput.prototype.init = function() {
	SuggestInput.base.init.call(this);
}

/**
 * 创建HTML节点
 */
SuggestInput.prototype.create = function() {
    this._html = document.createElement("div");
    if (this.getAttribute().showicon && 
    		this.getAttribute().showicon == "false") {
    	$(this._html).append("<div class='input-group'><input class='form-control'/></div>");
    } else {
    	$(this._html).append(
    		"<div class='input-group'>" +
    			"<input class='form-control'/>" +
    			"<div class='input-group-addon'>" +
        			"<span class='glyphicon glyphicon-search handleicon' style='cursor:pointer'></span>" +
        		"</div>" +
        	"</div>");
    }
}



SuggestInput.prototype.initLoad = function() {
    SuggestInput.base.initLoad.call(this);
    if (!$().autocomplete) {
        this.loadCSSFile("/public.common/webapi/common/autocomplete/jquery.autocomplete.css");
        this.loadScriptFile("/public.common/webapi/common/autocomplete/jquery.autocomplete.js");
    }
    var oInput = $("input",this._html);
    if (this._attr.describle) {
        oInput.attr("placeholder", this._attr.describle);
    }
    if (this._attr.text) {
        oInput[0].value = this._attr.text;
    }
    if (this._attr.disabled == "true") {
        this.setDisable();
    }

    var othis = this;
    oInput.bind("focus", function(e){
        othis.focus(e);
    });
    oInput.bind("blur", function(e){
        setTimeout(function(){
            othis.blur(e);
        },500);
    });
    //小图标点击事件
    $("span",this._html).bind("click", function(e){
        othis.clickIcon(e);
    });
    // 用插件實現自动建议输入
    oInput.autocomplete({
        width : (othis.getAttribute().suggestwidth)?
            othis.getAttribute().suggestwidth:0,
        control : this,
        focusshow: othis.getAttribute().focusshow,
        maxItemsToShow:othis.getAttribute().autocompleterownum?othis.getAttribute().autocompleterownum:10,
        mustMatch: (othis.getAttribute().mustmatch)? //默认必选
            eval(othis.getAttribute().mustmatch):true,
        formatItem: function(row, i, num) {
            return othis.formatItem(row, i, num);
        },
        onItemSelect : function(data) {
            othis.itemSelect(data.selectValue, data);
        }
    });

    if (this.getAttribute().params) {
    	if (typeof(this.getAttribute().params) == "object") {
    		this.getAttribute().params = JSON.stringify(this.getAttribute().params);
    	}
        var sParam = this.getAttribute().params.replaceAll("'","\"");
        var oParam = JSON.parse(sParam);
        this._queryParam = oParam;
    } else {
        this._queryParam = new Object();
    }
    if (this.getAttribute().type && this.getAttribute().type == "code") {
        if (!this.getAttribute().valuetag) this.getAttribute().valuetag = "cn";
        if (!this.getAttribute().displaytag) this.getAttribute().displaytag = "cn";
        if (!this.getAttribute().attributetag) this.getAttribute().attributetag = "hlp";
        if (!this.getAttribute().querytag) this.getAttribute().querytag = "cn";
        if (!this.getAttribute().idtag)
            this.getAttribute().idtag = "id";
        if (!this.getAttribute().pidtag)
            this.getAttribute().pidtag = "pid";
        if (!this.getAttribute().submittag) this.getAttribute().submittag =
            "{'" + this.getAttribute().path + "dm':'dm'}";
        this._queryParam.type = this.getAttribute().coderes;
        if (this.getAttribute().async == "true") {
            this._queryParam.pid = "-1";
            this._queryParam.child = "false";
        }
    }
    if (!this.getAttribute().parentallow) this.getAttribute().parentallow = "false";
    if (!this.getAttribute().check) this.getAttribute().check = "false";
	if (!this.getAttribute().tablerownum) this.getAttribute().tablerownum = "10";
    if (this.getAttribute().check == "true") {
        this._result = new Array();
    } else {
        this._result = new Object();
    }
    //默认值特殊处理
    this.buildDefault();
}

SuggestInput.prototype.buildDefault = function() {
	var sDefault = this.getAttribute()["default"];
	if (!sDefault) return;
    if (typeof(sDefault) == "object") {
        sDefault = JSON.stringify(sDefault);
    }
	var sDefault = sDefault.replaceAll("'","\"");
	var oDefault = JSON.parse(sDefault);
	var sPath = this.getAttribute().path;
	var value = "";
	if (sPath) {
		value = oDefault[sPath];
	}
	var oData = new Object();
	for (var i in oDefault) {
		oData[i] = oDefault[i];
	}
	this.setValue(value, oData);
}

/**
 * 格式化复选输入
 * @param q 文本框值
 */
SuggestInput.prototype.formatCheckInput = function (q) {
    var oResults = this.getResult();
    var sInput = q;
    for (var i = 0 ; i < oResults.length ; i++) {
        var sDisplay = oResults[i][this.getAttribute().displaytag];
        sInput = sInput.replaceAll(sDisplay+";", "");
    }
    return sInput.trim();
}

/**
 * 选中结果调用该方法
 * @param {} data
 */
SuggestInput.prototype.itemSelect = function(data, html) {
	//选择编码检查是否允许选择父节点
	if (this.getAttribute().type && this.getAttribute().type == "code") {
		if (!this.checkTreeData(data)) return;
	}
	//支持多选，手动输入获得结果. 需要设置为数组
	if (this.getAttribute().check == "true") {
        if (typeof(data.length) == "undefined") {
            this._result.push(data);
        } else {
            for (var i = 0 ; i < data.length ; i++) {
                this._result.push(data[i]);
            }
        }
	} else {
		this._result = data;
	}
	
	this.triggerAttributeEvent("itemselect", this._result, html);
	
	//调用认证方法
	this.setValidate(true);
    //不是必须匹配
    if (this.getAttribute().mustmatch == "false") {
        //什么也不做
        //此段代码执行的场景：当一个suggestinput即需要手工输入（可以不匹配也能使用）也需要通过建议输入都要求有效的情况，不加此代码会出现
        //输入的内容被清除的情况发生
    }else{
        //显示控件值
        //如果是选择的把输入的内容给去掉
        $("input",this.getHTML()).val("");
        this.show();
    }

}

/**
 * 如果是复选，回退键删掉一个元素
 */
SuggestInput.prototype.backInput = function(e) {
    if (this.getAttribute().check == "true") {
    	var text = $("input", this.getHTML()).val();
    	if (text.lastIndexOf(";") == (text.length -1)) {
    		if (this._result.length > 0) {
	            this._result.pop();
	            this.show();
	            e.preventDefault();
	        }
    	}
    }
}

/**
 * 如果是多选，移除某一个节点
 */
SuggestInput.prototype.removeSelect = function(id) {
    for (var i = 0 ; i < this._result.length ; i++) {
        var oResult = this._result[i];
        if (oResult.id == id) {
            this._result.splice(i, 1);
        }
    }
    this.show();
}

/**
 * 判断是否选中
 * @param id
 */
SuggestInput.prototype.hasSelect = function(id) {
    for (var i = 0 ; i < this._result.length ; i++) {
        var oResult = this._result[i];
        if (oResult.id == id) {
            return true;
        }
    }
    return false;
}

/**
 * 输入框显示结果
 */
SuggestInput.prototype.show = function(){
    var displayTag = this.getAttribute().displaytag;
	var text = "";
	if (this.getAttribute().check == "true") {
		for (var i = 0 ; i < this.getResult().length ; i++) {
			var checkNode = this.getResult()[i];
            text += checkNode[displayTag] + ";";
		}
//		if (text.length > 0) text = text.substring(0, text.length - 1);
	} else {
		text = this.getResult()[displayTag];
		if (!text) text = "";
	}
	if (this.getAttribute().mustmatch == "false") {
		text = $("input",this.getHTML()).val() + text;
	}
	$("input",this.getHTML()).val(text);
	$("input",this.getHTML())[0].lastSelected = text;
    var event = new Object();
    event.currentTarget = $("input",this.getHTML())[0];
    this.blur(event);
}

/**
 * 格式化显示结果
 * @param {} row
 * @param {} i
 * @param {} num
 */
SuggestInput.prototype.formatItem = function(row, i, num) {
	//如果有格式化事件
	if (this.getAttribute().formatitem) {
		return this.triggerAttributeEvent("formatitem",row, i, num);
	}
    /***解决当不需要下拉时的报错***/
    if(!this.getAttribute().displaytag){
        return;
    }
    /*******/
    var sText = this.valueItem(row, this.getAttribute().displaytag);
    var sAttr = "";
    if(this.getAttribute().attributetag){
        var attr = this.getAttribute().attributetag.split(",");
        for(var i = 0 ; i < attr.length ; i ++) {
            var rattr = this.valueItem(row, attr[i]);
            sAttr += rattr + ",";
        }
        if (sAttr != "") {
            sAttr = " ("+ sAttr.substring(0, sAttr.length-1) + ")";
        }
    }
    return "<font id='text'>" + sText +
        "</font><span style='color:#888'>" + sAttr + "</span>";
}

/**
 * 点击小图标
 */
SuggestInput.prototype.clickIcon = function(event) {
	if (this.isDisable()) return;
    if (this.getAttribute().iconclick) {
        this.triggerAttributeEvent("iconclick");
        return;
    }
    if (this.getAttribute().type == "code") {
    	var isLoadCheck = false;
        if (!this._treeObj) {
        	this.loadCodeTree();
        } else {
        	if (this.getAttribute().check == "true") {
        		isLoadCheck = true;
            }
        }
        if (this.getAttribute().iconclickreload == "true") this._treeObj.initLoad();
        this.showPanel(this._treeObj.getHTML());
        if (isLoadCheck) {
        	this.initTreeCheck();
        }
    } else { //type为data
		if (!this._tableObj) {
            this.loadDataTable();
        }
        if (this.getAttribute().iconclickreload == "true"){
        	this._tableObj.reload();
        	this.triggerAttributeEvent("beforequery");
        }
        
        this.showPanel(this._tableObj.getHTML());
    }
}



SuggestInput.prototype.loadCodeTree = function() {
    var that = this;
    var check = "false";
    if (this.getAttribute().check == "true") {
        check = "true";
    }
    
    this._treeObj =  Control.newInstance("Tree", {
    	id : this.getID() + "_tree",
        datasource : this.getAttribute().datasource,
        type : "code",
        coderes : this.getAttribute().coderes,
        params : JSON.stringify(this.getParam()),
        check : check,
        idTag : this.getAttribute().idTag,
        pidTag : this.getAttribute().pidTag,
        displaytag : this.getAttribute().displaytag,
        async : this.getAttribute().async,
        itemselect : function(oTree, e, treeId, treeNode) {
        	if (typeof(treeNode) == "undefined") return;
        	if (check == "true") {
        		that.onCheck(treeNode);
        	} else {
        		that.clickNode(treeNode);
        	}
        },
        oninitdata: function(oTree, oRecords){
        	that.triggerAttributeEvent("initdata", oRecords, oTree);
        },
        beforecheck: function(oTree, treeId, treeNode) {
        	if (typeof(treeNode) == "undefined") return;
        	return that.beforeCheck(treeNode);
        }
    });
    this._treeObj.init();
    $("body").append(this._treeObj.getHTML());
	
    this._treeObj.initLoad(function(oTree, oData) {
    	that.showPanel(that._treeObj.getHTML());
    	if (that.getAttribute().check == "true") {
    		that.initTreeCheck();
        }
    });
    
    $(this._treeObj.getHTML()).css({
    	"max-height":"400px",
    	"overflow":"auto",
    	"overflow-x":"hidden"
    });
}

SuggestInput.prototype.getTree = function () {
    return this._treeObj;
}


SuggestInput.prototype.showPanel = function(oContent) {
    var placement = "bottom";
    if (this.getAttribute().placement) {
        placement = this.getAttribute().placement;
    }
    if(this._tableObj){
    	this._tableObj.queryAndDisplay({});//每次打开对话框默认查询一次
    }
    var that = this;
    WinUtil.showPop(this.getHTML(), {
        placement:placement,
        trigger:"manual",
        handleable:true,
        html:true,
        content:oContent
    },function(control,option,e){//增加响应事件对于民警多选，每次展示界面时重新刷新一下所选中的内容
    	var queryname = that.getAttribute().queryname;
    	if(typeof(queryname) != "undefined" && (queryname == "officerm"||queryname == "druggerm")){
    		var oComponent=ToolUtil[queryname+that.getAttribute().id];
    		oComponent.getHandleClass().refreshSelectPersonTable();
    	}else{
    		//什么也不做
    	}    	
    });
}

/**
 * 选中单选树的节点
 * @param {} e
 * @param {} treeId
 * @param {} treeNode
 */
SuggestInput.prototype.clickNode = function(treeNode) {
	//判断是否能够选择父节点
	if (this.checkTreeData(treeNode)) {
		this.itemSelect(treeNode);
	}
	if (this.isValidate()) {
        WinUtil.closePop(this.getHTML());
	}
}

/**
 * 复选树选择前判断该节点是否可以选择.
 * @param {} treeId
 * @param {} treeNode
 */
SuggestInput.prototype.beforeCheck = function(treeNode) {
	return this.checkTreeData(treeNode);
}

/**
 * 复选树选择节点
 * @param {} e
 * @param {} treeId
 * @param {} treeNode
 */
SuggestInput.prototype.onCheck = function(treeNode) {
	$("input",this.getHTML()).val("");
	var checkNodes = this._treeObj.getCheckedNodes();
	//获得全选的父节点
	var checkAllParent = new Object();
	var checkNodes_n = new Array(); //处理后的选中节点
	for (var i = 0 ; i < checkNodes.length ; i++) {
		var checkNode = checkNodes[i];
		if (checkNode.check_Child_State == 2) {
			checkAllParent[checkNode.tId] = checkNode;
			if (!checkAllParent[checkNode.parentTId]) {
				checkNodes_n.push(checkNode);
			}
		}
	}
	//获得选中节点,如果父节点选中。不要子节点
	for (var i = 0 ; i < checkNodes.length ; i++) {
		var checkNode = checkNodes[i];
		if (checkNode.check_Child_State != 1  //半选中状态
		 && checkNode.check_Child_State != 2) {
		 	//父节点不是全选状态
			if (!checkAllParent[checkNode.parentTId]) {
				checkNodes_n.push(checkNode);
			}
		}
	}
    this.setResult(new Array());
	this.itemSelect(checkNodes_n);
}

SuggestInput.prototype.checkTreeData = function(data) {
	var parentAllow = this.getAttribute().parentallow;
	if (parentAllow == "false") {
		if (data.lower &&
			data.lower == "true") {
			this.setValidate(false);
			this.setError("请选择子节点.");
			this.showError();
			return false;
		}
	}
	return true;
}

SuggestInput.prototype.initTreeCheck = function() {
	var records = this.getResult();
	var dms = [];
	for (var i = 0 ; i < records.length ; i++) {
		dms.push(records[i].dm);
	}
	//选中编码
	var oData = this._treeObj.getResult();
	var ids = [];
	for (var i = 0 ; i < oData.length ; i++) {
		for (var j = 0 ; j < dms.length ; j++) {
			if (oData[i].dm == dms[j]) {
				ids.push(oData[i].id);
				break;
			}
		}
	}
	this._treeObj.setChecks(ids, true);
}


// ----------------------------table---------------------------//
/**
 * 当type为data, 点击加载icon点击表格
 */
SuggestInput.prototype.loadDataTable = function() {
    if (!this.getAttribute().defineaction) return;
    var that = this;
    var multiselect = false;
    if (this.getAttribute().check == "true") {
        multiselect = true;
    }
    this._tableObj =  Control.newInstance("ConfigDataGrid", {
        datasource : this.getAttribute().datasource,
        defineaction : this.getAttribute().defineaction,
        width: 800,
        rownum : this.getAttribute().tablerownum,
        params : JSON.stringify(this.getParam()),
        multiselect : multiselect,
        onselectrow: function(oTable, rowid, status) {
            if (typeof(rowid) == "undefined") return;
            if (oTable.getAttribute().multiselect) { //多选
                if (status) {
                    that.itemSelect(oTable.getData(rowid));
                } else {
                    that.removeSelect(rowid);
                }
            } else { //单选
                var oData = oTable.getData(rowid);
                that.itemSelect(oData);
                WinUtil.closePop(that.getHTML());
            }
        },
        gridcomplete: function(oTable) { //翻页默认选中已有行
            if (typeof(oTable) != "object") return;
            var ids = oTable.getDataIDs();
            for (var i = 0 ; i < ids.length ; i++) {
                var id = ids[i];
                if (that.hasSelect(id)) {
                    oTable.setSelection(id, false);
                }
            }
        },
        onselectall: function(oTable, rowids, status) { //全选
        	if (typeof(oTable) == "number") return;
        	that.triggerAttributeEvent("gridselectall", oTable, rowids, status);
    		for(var i = 0 ; i < rowids.length ; i++){
                if (status) {
                   that.itemSelect(oTable.getData(rowids[i]));
                } else {
                   that.removeSelect(rowids[i]);
            	} 
        	}
        },
        beforeshow: function(oTable, oRecords) {
        	that.triggerAttributeEvent("initdata", oRecords, oTable);
        }
    });
    this._tableObj.init();
    $("body").append(this._tableObj.getHTML());
    this._tableObj.initLoad();
    this.triggerAttributeEvent("beforequery");

    this._tableObj.queryAndDisplay({});
}


SuggestInput.prototype.validateControl = function(sValue) {
	if (this.getAttribute().selfValidate == "false") {
		return true;
	}
	//验证录入信息中不能有非法字符
	var specialSignal = new Array("'","%","_","&");
	for(var index=0 ; index < specialSignal.length ; index++){
		if(sValue.indexOf(specialSignal[index]) != -1){
			this.setValidate(false);
			this.setError("请不要录入单引号或者_，%，&等其他特殊符号！");
			return false;
		}	
	}
	if(sValue.indexOf("<") != -1 || sValue.indexOf(">") != -1){
		this.setValidate(false);
		this.setError("请不要录入<>符号！");
		return false;
	}
	return true;
}

/**
 * 获得选中结果对象
 * @return {}
 */
SuggestInput.prototype.getResult = function() {
	return this._result;
}

SuggestInput.prototype.setResult = function(oResult) {
	this._result = oResult;
}

/**
 * 获取当前控件的值。需要提交到数据库
 */
SuggestInput.prototype.getValue = function(oData) {
    var valueTag = this.getAttribute().valuetag;
	//不是必须匹配
	if (this.getAttribute().mustmatch == "false") {
		return $("input", this.getHTML()).val();
	}
    this.buildSubmit(oData);
	if (this.getAttribute().check == "true") { //复选，逗号分隔值
		var value = "";
		for (var i = 0 ; i < this.getResult().length ; i++) {
			var oResult = this.getResult()[i];
			value += oResult[valueTag] + ",";
		}
		if (value.length > 1) {
			value = value.substring(0, value.length - 1);
		}
		return value;
	} else {
		if (typeof(this.getResult()[valueTag]) != "undefined") {
			return this.getResult()[valueTag];
		}
	}
	return "";
}

/**
 * 设置当前控件的值，提交到数据库
 */
SuggestInput.prototype.setValue = function(value, oData) {
    SuggestInput.base.setValue.call(this);
	if (!value || value == "") {
        if (this.getAttribute().check == "true")
		    this.setResult(new Array());
        else
            this.setResult(new Object());
		$("input", this.getHTML()).val(value);
		if (this._tableObj) this._tableObj.reload(false);
		if (this._treeObj) this._treeObj.reload();
		return;
	}
	//不是必须匹配
	if (this.getAttribute().mustmatch == "false") {
		$("input", this.getHTML()).val(value);
		return;
	}
    this.buildResult(value, oData);
	this.show();
}


SuggestInput.prototype.buildValue = function(value) {
    var oResult;
    var valueTag = this.getAttribute().valuetag;
    if (this.getAttribute().check == "true") {
        oResult = new Array();
        var values = value.split(",");
        for (var i = 0 ; i < values.length ; i++) {
            var rlt = new Object();
            rlt[valueTag] = values[i];
            oResult.push(rlt);
        }
    } else {
        oResult = new Object();
        oResult[valueTag] = value;
    }
    return oResult;
}

/**
 * 设置显示
 */
SuggestInput.prototype.setDisplay = function(value) {
	$("input",this._html).val(value);
}

/**
 * 获得显示信息
 */
SuggestInput.prototype.getDisplay = function() {
	return $("input",this._html).val();
}

/**
 * 设置查询参数
 */
SuggestInput.prototype.setParam = function(oParam) {
	this._queryParam = oParam;
	if (this._tableObj) {
		this._tableObj.setParam(oParam);
	}
	if (this._treeObj) {
		this._treeObj.setParam(oParam);
	}
}

/**
 * 获得查询参数
 */
SuggestInput.prototype.getParam = function() {
	return this._queryParam;
}

/**
 * 设置为可编辑
 */
SuggestInput.prototype.setEnable = function(){
	SuggestInput.base.setEnable.call(this);
	$("input",this._html)[0].disabled = false;
	$(".input-group-addon",this._html).show();
}

/**
 * 设置为只读
 */
SuggestInput.prototype.setDisable = function(){
	SuggestInput.base.setDisable.call(this);
	$("input",this._html).attr("disabled","true");
	$(".input-group-addon",this._html).hide();
}

